#
# 聊天客户端
# 
# 【重点】可以在同一 socket 上起两个线程，一个发送，一个接收
# 


import socket
from threading import Thread

IP = '127.0.0.1'
PORT = 5000

cs = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
cs.connect((IP, PORT))

msg = cs.recv(50)
print(msg.decode('utf-8'))

is_quit = [False]

def send_msg(socket):
    """接收键盘输入并发送的线程"""
    ms = ''
    while ms != 'q':
        ms = input(":> ")
        socket.send(bytes(ms, 'utf-8'))
    is_quit[0] = True


def receive_msg(socket):
    """接收服务器发来的消息，并打印的线程"""
    while not is_quit[0]:
        try:
            mc = socket.recv(1024)
            if len(mc) <= 0:
                break
            print(mc.decode('utf-8'))
        except:
            print("Receive message error.")


ts = Thread(target=send_msg, args=(cs,))
ts.start()
tc = Thread(target=receive_msg, args=(cs,))
tc.start()